local UIBase = require("view.UIBase")
local SelectedUI = class("SelectedUI", UIBase)
local GameUtils = require("utils.GameUtils")
local UIUtil = require("utils.UIUtil")
local Vector2 = require("utils.Vector2")
local Vector3 = require("utils.Vector3")

function SelectedUI:ctor(actor)
    self._actor = actor
    self._lastPos = Vector2.new(0, 0)
    local resource = {
        path = "Prefabs/UI",
        name = "SelectedUI",
        canvas = 1
    }
    SelectedUI.super.ctor(self, resource)
end

function SelectedUI:start()
    self._rect = self.gameObject:GetComponent(typeof(CS.UnityEngine.RectTransform))
    self._uiCamera = G_UIManager:getUICamera()
    self._mainCamera = UIUtil.getMainCamera()
    self._parentRect = self.transform.parent:GetComponent(typeof(CS.UnityEngine.RectTransform))
    self:updatePosition()
    UIUtil.addButtonClick(self._btn.transform, handler(self, self._onTouchClick))
end

function SelectedUI:update()
    self:updatePosition()
end

function SelectedUI:updatePosition()
    local trans = self._actor.transform
    local screenPoint = self._mainCamera:WorldToScreenPoint(trans.position)
    if Vector3.equal(screenPoint, self._lastPos) then
        return
    end
    self._lastPos = screenPoint
    local screenPoint2 = Vector2.new(screenPoint.x, screenPoint.y)
    local outPos = G_UIManager:ScreenPointToLocalPointInRectangle(self._parentRect, screenPoint2, self._uiCamera)
    self._rect.localPosition = Vector3.new(outPos.x, outPos.y + 50, 0)
end

function SelectedUI:setCallback(callback)
    self._callback = callback
end

function SelectedUI:_onTouchClick()
    printDebug("点击选择目标")
    if self._callback then
        self._callback(self._actor:getId())
    end
end

return SelectedUI
